package com.itheima.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2020/11/10 11:28
 **/
@Order(0)
//@Component
public class LoginFilter implements GlobalFilter {
    /**
     * @param exchange  对原生的请求 和 响应对象做了封装  request  和 response
     * @param chain  过滤器链对象
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取请求对象， 获取响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 2. 通过请求对象判断是否包含token参数 及 参数是否为 admin
        Map<String, String> paramsMap = request.getQueryParams().toSingleValueMap();
        String token = paramsMap.get("token");
        if("admin".equals(token)){
            // 3. 如果判断成功  则 调用过滤器链对象放行
            return chain.filter(exchange);
        }
        // 4. 如果判断失败  则 调用响应对象终止请求
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
